package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.H5User;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.dto.H5UserDetailDTO;
import com.ruoyi.system.dto.H5UserProjectDTO;
import com.ruoyi.system.enums.H5UserStatusEnum;
import com.ruoyi.system.enums.ProjectStatusEnum;
import com.ruoyi.system.mapper.H5UserMapper;
import com.ruoyi.system.mapper.ProjectMapper;
import com.ruoyi.system.service.IH5UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * H5用户服务实现类
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class H5UserServiceImpl extends ServiceImpl<H5UserMapper, H5User> implements IH5UserService {

    @Resource
    private ProjectMapper projectMapper;

    @Override
    public H5User selectUserByUsername(String userName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<H5User>()
                .eq(H5User::getUserName, userName)
                .eq(H5User::getDelFlag, "0")); // 未删除
    }

    @Override
    public H5User selectUserByPhoneNumber(String phoneNumber) {
        return baseMapper.selectOne(new LambdaQueryWrapper<H5User>()
                .eq(H5User::getPhonenumber, phoneNumber)
                .eq(H5User::getDelFlag, "0"));
    }

    @Override
    public H5User selectUserByThirdOpenid(String thirdOpenid) {
        return baseMapper.selectOne(new LambdaQueryWrapper<H5User>()
                .eq(H5User::getThirdOpenid, thirdOpenid)
                .eq(H5User::getDelFlag, "0"));
    }

    @Override
    public int insertH5User(H5User h5User) {
        h5User.setCreateTime(DateUtils.getNowLocalDateTime());
        h5User.setUpdateTime(DateUtils.getNowLocalDateTime());
        h5User.setDelFlag("0"); // 默认未删除
        h5User.setStatus(h5User.getStatus() == null ? "2" : h5User.getStatus()); // 默认未验证手机号
        return baseMapper.insert(h5User);
    }

    @Override
    public int updateH5User(H5User h5User) {
        h5User.setUpdateTime(DateUtils.getNowLocalDateTime());
        return baseMapper.updateById(h5User);
    }

    @Override
    public int updateLoginInfo(Long userId, String loginIp, String loginDevice) {
        H5User user = new H5User();
        user.setUserId(userId);
        user.setLoginIp(loginIp);
        user.setLoginDate(DateUtils.getNowLocalDateTime());
        user.setLastLoginDevice(loginDevice);
        user.setUpdateTime(DateUtils.getNowLocalDateTime());
        return baseMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean disableH5User(Long userId, String operator) {
        log.info("开始禁用H5用户账号，用户ID: {}, 操作者: {}", userId, operator);
        
        // 查询用户信息
        H5User h5User = baseMapper.selectById(userId);
        if (h5User == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 检查用户是否已删除
        if (Objects.equals(h5User.getDelFlag(), "2")) {
            throw new ServiceException("用户已被删除，无法操作");
        }
        
        // 检查用户当前状态
        if (Objects.equals(h5User.getStatus(), H5UserStatusEnum.DISABLED.getCode())) {
            throw new ServiceException("用户已被禁用，无需重复操作");
        }
        
        // 更新用户状态为禁用
        H5User updateUser = new H5User();
        updateUser.setUserId(userId);
        updateUser.setStatus(H5UserStatusEnum.DISABLED.getCode());
        updateUser.setUpdateBy(operator);
        updateUser.setUpdateTime(DateUtils.getNowLocalDateTime());
        
        int result = baseMapper.updateById(updateUser);
        
        if (result > 0) {
            log.info("H5用户账号禁用成功，用户ID: {}, 操作者: {}", userId, operator);
            return true;
        } else {
            log.error("H5用户账号禁用失败，用户ID: {}, 操作者: {}", userId, operator);
            throw new ServiceException("禁用用户账号失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean enableH5User(Long userId, String operator) {
        log.info("开始启用H5用户账号，用户ID: {}, 操作者: {}", userId, operator);
        
        // 查询用户信息
        H5User h5User = baseMapper.selectById(userId);
        if (h5User == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 检查用户是否已删除
        if (Objects.equals(h5User.getDelFlag(), "2")) {
            throw new ServiceException("用户已被删除，无法操作");
        }
        
        // 检查用户当前状态
        if (Objects.equals(h5User.getStatus(), H5UserStatusEnum.NORMAL.getCode())) {
            throw new ServiceException("用户状态正常，无需重复操作");
        }
        
        // 更新用户状态为正常
        H5User updateUser = new H5User();
        updateUser.setUserId(userId);
        updateUser.setStatus(H5UserStatusEnum.NORMAL.getCode());
        updateUser.setUpdateBy(operator);
        updateUser.setUpdateTime(DateUtils.getNowLocalDateTime());
        
        int result = baseMapper.updateById(updateUser);
        
        if (result > 0) {
            log.info("H5用户账号启用成功，用户ID: {}, 操作者: {}", userId, operator);
            return true;
        } else {
            log.error("H5用户账号启用失败，用户ID: {}, 操作者: {}", userId, operator);
            throw new ServiceException("启用用户账号失败");
        }
    }

    @Override
    public List<H5UserProjectDTO> getProjectsByH5UserId(Long h5UserId) {
        log.info("查询H5用户关联的项目，H5用户ID: {}", h5UserId);
        
        if (h5UserId == null) {
            return new ArrayList<>();
        }
        
        // 查询关联的项目
        List<Project> projects = projectMapper.selectList(new LambdaQueryWrapper<Project>()
                .eq(Project::getH5UserId, h5UserId)
                .eq(Project::getDeleted, 0) // 未删除
                .orderByDesc(Project::getCreateTime)); // 按创建时间倒序
        
        List<H5UserProjectDTO> projectDTOs = new ArrayList<>();
        for (Project project : projects) {
            H5UserProjectDTO dto = new H5UserProjectDTO();
            dto.setId(project.getId());
            dto.setProjectNo(project.getProjectNo());
            dto.setProjectName(project.getProjectName());
            dto.setCreateTime(project.getCreateTime());
            
            // 根据项目进度设置项目状态
            Integer progress = project.getProgress();
            if (progress != null) {
                if (progress == 8) {
                    // 结单
                    dto.setProjectStatus(ProjectStatusEnum.CLOSED.getCode());
                    dto.setProjectStatusDesc(ProjectStatusEnum.CLOSED.getDesc());
                } else if (progress == 7) {
                    // 完工
                    dto.setProjectStatus(ProjectStatusEnum.COMPLETED.getCode());
                    dto.setProjectStatusDesc(ProjectStatusEnum.COMPLETED.getDesc());
                } else {
                    // 进行中
                    dto.setProjectStatus(ProjectStatusEnum.IN_PROGRESS.getCode());
                    dto.setProjectStatusDesc(ProjectStatusEnum.IN_PROGRESS.getDesc());
                }
            } else {
                // 默认进行中
                dto.setProjectStatus(ProjectStatusEnum.IN_PROGRESS.getCode());
                dto.setProjectStatusDesc(ProjectStatusEnum.IN_PROGRESS.getDesc());
            }
            
            projectDTOs.add(dto);
        }
        
        log.info("查询到H5用户关联的项目数量: {}", projectDTOs.size());
        return projectDTOs;
    }

    @Override
    public H5UserDetailDTO getH5UserDetail(Long userId) {
        log.info("获取H5用户详情，用户ID: {}", userId);
        
        // 查询H5用户基本信息
        H5User h5User = baseMapper.selectById(userId);
        if (h5User == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 查询关联的项目
        List<H5UserProjectDTO> projects = getProjectsByH5UserId(userId);
        
        // 构建详情DTO
        H5UserDetailDTO detailDTO = new H5UserDetailDTO();
        detailDTO.setH5User(h5User);
        detailDTO.setProjects(projects);
        
        log.info("获取H5用户详情成功，用户ID: {}, 关联项目数量: {}", userId, projects.size());
        return detailDTO;
    }
}